#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'定制类：定制类的一些特性'


class Student(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.__class__.__name__

    __repr__ = __str__

    def __getattr__(self, attr):
        if attr == 'age':
            return  12 # 还可以返回函数 lambda: 25
        raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)


s = Student('Michael')
print(s.age)  # 11
print(s.sex)  # None


# print(s) # <__main__.Student object at 0x000001A3190B9898>

# 重写了__str__方法后：
# print(s) # Student

class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1  # 初始化两个计数器a,b

    def __iter__(self):
        return self

    def __next__(self):
        self.a, self.b = self.b, self.a + self.b
        if self.a > 1000:  # 退出循环
            raise StopIteration()
        return self.a

    def __getitem__(self, item):
        if isinstance(item, int):
            a, b = 1, 1
            for x in range(item):
                a, b = b, a + b
            return a
        if isinstance(item, slice):
            start = item.start
            stop = item.stop
            if start is None:
                start = 0
            a, b = 1, 1
            L = []
            for x in range(stop):
                if x >= start:
                    L.append(a)
                a, b = b, a + b
            return L


fib = Fib()
'''
for f in fib:
    print(f) # 1 1 2 3 5 8 ...
'''

# 没重写__getitem__之前
# print(fib[4]) # TypeError: 'Fib' object does not support indexing

# 重写后
# print(fib[4]) # 5
# print(fib[:3]) # [1, 1, 2]
